<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.orderId" placeholder="订单号" style="width: 250px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-select v-model="keywords" placeholder="域名后缀" clearable class="filter-item" style="width: 150px">
        <el-option v-for="(it,index) in keywordsOptions" :key="index" :label="it" :value="it" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="订单状态" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in statusOptions" :key="item.index" :label="item.value" :value="item.index" />
      </el-select>
      <el-date-picker
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
        value-format="timestamp"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="用户ID" prop="id" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="域名" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.domain }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.realName || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱数量" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.number || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.telphone || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单ID" min-width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="150px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.status | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="日期" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ renderTime(row.createAt ) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="edit(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :limit.sync="listQuery.pageSize"
      :page.sync="listQuery.pageIndex"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { selectOrder } from '@/api/orders'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

import { renderTime } from '@/utils/util'
// import { phoneReg, mailReg } from '@/utils/validate.js'

// 总订单状态：0 订单处理中 1 订单完成 -1 订单支付失败 2订单已确认 3银行转账待确认
// 域名子订单 ：1待审核 2 审核通过 3 订单上传完成 -1 审核失败 0初始化
const statusOptions = [
  { index: 0, value: '订单处理中' },
  { index: 1, value: '订单完成' },
  { index: -1, value: '订单支付失败' },
  { index: 2, value: '订单已确认' },
  { index: 3, value: '银行转账待确认' }
]
// const statusOptions = [
//   { index: 0, value: '资料待完善' },
//   { index: 1, value: '待审核' },
//   { index: 2, value: '审核通过' },
//   { index: 3, value: '文件已上传' },
//   { index: -1, value: '审核失败' }
// ]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.index] = cur.value
  return acc
}, {})

export default {
  name: 'Orders',
  components: { Pagination },
  directives: { waves },
  filters: {
    typeFilter(index) {
      return calendarTypeKeyValue[index]
    }
  },
  props: {
    typeValue: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      keywordsOptions: [],
      keywords: '',
      total: 0,
      listLoading: true,
      listQuery: {
        type: undefined, // 1：域名 2：邮箱 3：网站4：安全
        orderId: '',
        pageIndex: 1,
        pageSize: 10,
        keywords: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      date: '',
      statusOptions,
      sord: '-id',
      status: ''
    }
  },
  watch: {
    typeValue: {
      handler(newV) {
        this.listQuery.type = newV
        this.getList()
      },
      immediate: true
    },
    keywords: {
      handler(newV) {
        if (newV) {
          newV = newV.replace('*', '%')
          this.listQuery.keywords = newV
        } else {
          this.listQuery.keywords = ''
        }
      },
      immediate: true
    },
    date: {
      handler: function(newV) {
        console.log(newV)
        if (newV && newV.length === 2) {
          this.listQuery.startTime = this.renderTime(newV[0], '{y}-{m}-{d}')
          // 一天是8640000毫秒差
          this.listQuery.endTime = this.renderTime(newV[1] + 86400000, '{y}-{m}-{d}')
          console.log(this.renderTime(newV[1], '{y}-{m}-{d}'))
        } else if (newV && newV.length !== 2) {
          this.$message({
            type: 'error',
            message: '日期选择出错'
          })
        } else {
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
      }
    },
    status: {
      handler(newV) {
        if (typeof (newV) === 'number') {
          this.temp.status = newV
          if (newV === -1) {
            this.approvalFailed = true
          }
        }
      }
    }
  },
  created() {
    this.keywordsOptions = this.$store.getters.list.map(item => item.replace('%', '*'))
  },
  methods: {
    renderTime,
    // 1：域名 2：邮箱 3：网站4：安全
    getList(sort) {
      this.listLoading = true
      // +id -id
      if (sort && sort.length === 3) {
        if (sort === '+id') { // 正序
          selectOrder(this.listQuery).then(response => {
            function add(a, b) {
              return a.id - b.id
            }
            this.list = response.data.list.sort(add)
            this.total = response.data.totalRecord
          })
        } else if (sort === '-id') { // 倒叙
          selectOrder(this.listQuery).then(response => {
            function add(a, b) {
              return b.id - a.id
            }
            this.list = response.data.list.sort(add)
            this.total = response.data.totalRecord
          })
        }
      } else {
        selectOrder(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.totalRecord
        })
      }
      this.listLoading = false
    },
    searchList() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    edit(row) {
      this.$message({
        message: '编辑接口正在开发',
        type: 'error'
      })
      //   this.temp.orderId = row.orderId
      //   this.temp.domain = row.domain
      //   this.temp.realName = row.realName
      //   this.temp.email = row.email
      //   this.temp.telphone = row.telphone
      //   this.dialogStatus = 'update'
      //   this.dialogFormVisible = true
      //   this.statusOptions.forEach(item => {
      //     if (item.index === row.status) {
      //       this.status = item.value
      //       this.temp.status = row.status
      //     }
      //   })
    //   this.$nextTick(() => {
    //     this.$refs['dataForm'].clearValidate()
    //   })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    // 按照订单的id进行排序
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.sort = '+id'
      } else {
        this.sort = '-id'
      }
      this.getList(this.sort)
    },

    getSortClass: function(key) {
      const sort = this.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style lang="scss">
    @import '@/assets/scss/mixin.scss';
    .el-form-item--medium{
      .el-form-item__content{
        display: flex;
        align-items: center;
        .el-input{
          &+.el-button{
            margin-left: 0.625rem;
          }
        }
        .el-button{
          &:not(:first-child){
            margin-left: 0.625rem;
          }
        }
      }
    }
</style>
